package tmc.app.admin;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import org.json.JSONException;
import org.json.JSONObject;

import tmc.app.data.DBHandler;
import tmc.app.data.GlobalVariables;
import tmc.app.data.ObjRecordData;
import tmc.app.data.ObjUser;
import tmc.app.data.ProcessData;
import tmc.app.luckydraw.R;
import tmc.app.luckydraw.R.layout;
import tmc.app.luckydraw.R.menu;
import tmc.app.main.MainActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

public class ActivityAdmin extends Activity {

    private ImageView btn_home;
	private ImageView btn_dongbo;
	private ImageView btn_save;
	private EditText percent_win;
	private EditText edt_gifts_rel1;
	private EditText edt_results_rel1;
	private EditText edt_gifts_rel2;
	private EditText edt_results_rel2;
	private EditText edt_gifts_rel3;
	private EditText edt_results_rel3;
	private EditText edt_gifts_rel4;
	private EditText edt_results_rel4;
	private EditText edt_gifts_rel5;
	private EditText edt_results_rel5;
	private Context mContext;
	private DBHandler db;
	private boolean postCompleted = false;
	private Dialog mDialog;
	private Activity mActivity;

	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_admin);

		mContext = this;
		mActivity = this;
        initLayouts();
        initEvents();
        try {
            getDataToEdt();
//             loadRecordUserFromDb();
		} catch (Exception e) {
			// TODO: handle exception
		}
    }

	public void showDialog() {
		if (mActivity != null) {
			if (mDialog != null)
				mDialog.dismiss();
			mDialog = new Dialog(mActivity, android.R.style.Theme_Translucent_NoTitleBar);
		}
		if (mDialog != null)
			ProcessData.showDialogLoading(mDialog, "");
	}

	public void closeDialog() {
		if (mDialog != null)
			mDialog.dismiss();
	}
	
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
    public void initLayouts()
    {


		db = new DBHandler(mContext);
		
    	btn_home = (ImageView)findViewById(R.id.btn_home);
    	btn_dongbo = (ImageView)findViewById(R.id.btn_dongbo);
    	btn_save = (ImageView)findViewById(R.id.btn_save);
    	percent_win = (EditText)findViewById(R.id.percent_win);
    	edt_gifts_rel1 = (EditText)findViewById(R.id.edt_gifts_rel1);
    	edt_results_rel1 = (EditText)findViewById(R.id.edt_results_rel1);
    	edt_gifts_rel2 = (EditText)findViewById(R.id.edt_gifts_rel2);
    	edt_results_rel2 = (EditText)findViewById(R.id.edt_results_rel2);
    	edt_gifts_rel3 = (EditText)findViewById(R.id.edt_gifts_rel3);
    	edt_results_rel3 = (EditText)findViewById(R.id.edt_results_rel3);
    	edt_gifts_rel4 = (EditText)findViewById(R.id.edt_gifts_rel4);
    	edt_results_rel4 = (EditText)findViewById(R.id.edt_results_rel4);
    	edt_gifts_rel5 = (EditText)findViewById(R.id.edt_gifts_rel5);
    	edt_results_rel5 = (EditText)findViewById(R.id.edt_results_rel5);
    }
    
    public void loadRecordUserFromDb()
    {    
    	GlobalVariables.indexUser = 0;
    	GlobalVariables.lstUser.clear();
    	GlobalVariables.lstUser = db.getAllItemsRecordUser();
    }
    
    public void loadRecordDataFromDb()
    {
	resetVariblesPost();
	GlobalVariables.lstData.clear();
	GlobalVariables.lstData = db.getAllItemsRecordData();
    }
    
    public void initEvents()
    {
    	btn_dongbo.setOnClickListener(onClickListener);
    	btn_save.setOnClickListener(onClickListener);
    	btn_home.setOnClickListener(onClickListener);
    }
    
    public OnClickListener onClickListener = new OnClickListener()
    {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.btn_save:
				ProcessData.ringPhone(mActivity);
				saveToDb();
				break;
			case R.id.btn_home:
				ProcessData.ringPhone(mActivity);
				moveToHome();
				break;
			case R.id.btn_dongbo:
				loadRecordUserFromDb();
				loadRecordDataFromDb();
				ProcessData.ringPhone(mActivity);
				showDialog();
				onPostToServer();
				break;
			default:
				break;
			}
		}
    	
    };
    
    public void onBackPressed() {};
    
    public void onPostToServer()
    {
		if (ProcessData.isInternet(mActivity)) {
			try {
				if(GlobalVariables.lstData.size()!=0)
				{
				  postToServer();
				}else{
				  if(GlobalVariables.lstUser.size() != 0)
				  {
					postRecordUserToServer();
				  }else{
					closeDialog();
// 					deleteAllData();
// 					showDialogDeleteData();
				  }
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
		} else {
			showDialogConnection(0);
		}
    }
    
    public void setDataFromEdt()
    {
    	
    }
    
    public void getDataToEdt()
    {
    	if(GlobalVariables.defaultRecordData != null)
    	{
        	percent_win.setText(GlobalVariables.defaultRecordData.getPercent());
    		edt_gifts_rel1.setText(GlobalVariables.defaultRecordData.getDataAo());
        	edt_results_rel1.setText(GlobalVariables.defaultRecordData.getResultAo());
        	edt_gifts_rel2.setText(GlobalVariables.defaultRecordData.getDataBalo());
        	edt_results_rel2.setText(GlobalVariables.defaultRecordData.getResultBalo());
        	edt_gifts_rel3.setText(GlobalVariables.defaultRecordData.getDataSotay());
        	edt_results_rel3.setText(GlobalVariables.defaultRecordData.getResultSotay());
        	edt_gifts_rel4.setText(GlobalVariables.defaultRecordData.getDataBut());
        	edt_results_rel4.setText(GlobalVariables.defaultRecordData.getResultBut());
        	edt_gifts_rel5.setText(GlobalVariables.defaultRecordData.getDataMockhoa());
        	edt_results_rel5.setText(GlobalVariables.defaultRecordData.getResultMockhoa());
    	}
    }
    
    public void showDialogDeleteData() {
		final Dialog dialog = new Dialog(mActivity, android.R.style.Theme_Black);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.layout_dialog_del);
		dialog.getWindow().setBackgroundDrawableResource(
				R.drawable.bg_transparent);
		Button btnOpt1 = (Button) dialog.findViewById(R.id.btn_yes);
		Button btnOpt2 = (Button) dialog.findViewById(R.id.btn_no);
		TextView txtName = (TextView) dialog.findViewById(R.id.txt_name);

		btnOpt1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// thoat
				ProcessData.ringPhone(mActivity);
				deleteAllData();
				dialog.dismiss();
			}
		});

		btnOpt2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				ProcessData.ringPhone(mActivity);
				dialog.dismiss();
			}
		});

		dialog.setCancelable(false);
		dialog.show();

	}
    
    public void showDialogConnection(final int type) {
		final Dialog dialog = new Dialog(mActivity, android.R.style.Theme_Black);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.layout_dialog_internet);
		dialog.getWindow().setBackgroundDrawableResource(
				R.drawable.bg_transparent);
		Button btnOpt1 = (Button) dialog.findViewById(R.id.btn_yes);
		Button btnOpt2 = (Button) dialog.findViewById(R.id.btn_no);
		TextView txtName = (TextView) dialog.findViewById(R.id.txt_name);

		btnOpt1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// thoat
				ProcessData.ringPhone(mActivity);
				System.exit(0);
			}
		});

		btnOpt2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				ProcessData.ringPhone(mActivity);
				switch (type) {
				case 0:// loadData
					onPostToServer();
					break;
				}
				dialog.dismiss();
			}
		});

		dialog.setCancelable(false);
		dialog.show();

	}
    
    public void moveToHome()
    {
		Intent intent = new Intent(this, MainActivity.class);
		startActivity(intent);
		overridePendingTransition(android.R.anim.slide_in_left,
				android.R.anim.slide_out_right);
		finish();
    }
    
    public void deleteAllData()
    {
    	db.deleteAllItemsRecordData();
    	db.deleteAllRecordUsers();
    }
    
    public void saveToDb()
    {
    	if(edt_gifts_rel1.getText().toString().equals("") 
    			|| Integer.parseInt(edt_gifts_rel1.getText().toString()) < Integer.parseInt(edt_results_rel1.getText().toString()))
    	{
    		ProcessData.showDialogThongbao(mContext, getResources().getString(R.string.txt_inputErr));
    		
    	}else if(edt_gifts_rel2.getText().toString().equals("") 
    			|| Integer.parseInt(edt_gifts_rel2.getText().toString()) < Integer.parseInt(edt_results_rel2.getText().toString()))
    	{
    		ProcessData.showDialogThongbao(mContext, getResources().getString(R.string.txt_inputErr));
    		
    	}else if(edt_gifts_rel3.getText().toString().equals("") 
    			|| Integer.parseInt(edt_gifts_rel3.getText().toString()) < Integer.parseInt(edt_results_rel3.getText().toString()))
    	{
    		ProcessData.showDialogThongbao(mContext, getResources().getString(R.string.txt_inputErr));
    		
    	}else if(edt_gifts_rel4.getText().toString().equals("") 
    			|| Integer.parseInt(edt_gifts_rel4.getText().toString()) < Integer.parseInt(edt_results_rel4.getText().toString()))
    	{

    		ProcessData.showDialogThongbao(mContext, getResources().getString(R.string.txt_inputErr));
    	}else if(edt_gifts_rel5.getText().toString().equals("") 
    			|| Integer.parseInt(edt_gifts_rel5.getText().toString()) < Integer.parseInt(edt_results_rel5.getText().toString()))
    	{

    		ProcessData.showDialogThongbao(mContext, getResources().getString(R.string.txt_inputErr));
    	}else if(percent_win.getText().toString().equals("") || Integer.parseInt(percent_win.getText().toString()) < 0 || Integer.parseInt(percent_win.getText().toString()) > 101)
    	{

    		ProcessData.showDialogThongbao(mContext, getResources().getString(R.string.txt_inputErr));
    	}
    	else{
			Log.v("DATA", "check update");
			ObjRecordData data = new ObjRecordData(getCurrentDate(), 
					percent_win.getText().toString(), 
					edt_gifts_rel1.getText().toString(), edt_results_rel1.getText().toString(), 
					edt_gifts_rel2.getText().toString(), edt_results_rel2.getText().toString(), 
					edt_gifts_rel3.getText().toString(), edt_results_rel3.getText().toString(), 
					edt_gifts_rel4.getText().toString(), edt_results_rel4.getText().toString(), 
					edt_gifts_rel5.getText().toString(), edt_results_rel5.getText().toString());
			db.updateRecordData(data);
			setDataGame(data);
			GlobalVariables.lstData.clear();
			GlobalVariables.lstData = db.getAllItemsRecordData();
			ProcessData.showDialogThongbao(mContext, getResources().getString(R.string.txt_saveDb));
			
			GlobalVariables.saveGiaiThuong(mActivity, GlobalVariables.AO, Integer.parseInt(data.getDataAo()));
			GlobalVariables.saveGiaiThuong(mActivity, GlobalVariables.BALO, Integer.parseInt(data.getDataBalo()));
			GlobalVariables.saveGiaiThuong(mActivity, GlobalVariables.VIET, Integer.parseInt(data.getDataBut()));
			GlobalVariables.saveGiaiThuong(mActivity, GlobalVariables.MOC_KHOA, Integer.parseInt(data.getDataMockhoa()));
			GlobalVariables.saveGiaiThuong(mActivity, GlobalVariables.SO_TAY, Integer.parseInt(data.getDataSotay()));
			
			Log.v("TEST","ADMIN edt_gifts_rel4 " + edt_gifts_rel4.getText().toString());
			Log.v("TEST","ADMIN AO " + data.getDataAo());
			Log.v("TEST","ADMIN AO loadCountGiaiThuong " + GlobalVariables.loadCountGiaiThuong(mActivity, GlobalVariables.AO));
			Log.v("TEST","ADMIN BALO " + data.getDataBalo());
			Log.v("TEST","ADMIN BALO loadCountGiaiThuong " + GlobalVariables.loadCountGiaiThuong(mActivity, GlobalVariables.BALO));
			Log.v("TEST","ADMIN VIET " + data.getDataBut());
			Log.v("TEST","ADMIN VIET loadCountGiaiThuong " + GlobalVariables.loadCountGiaiThuong(mActivity, GlobalVariables.VIET));
			Log.v("TEST","ADMIN SO_TAY " + data.getDataSotay());
			Log.v("TEST","ADMIN SO_TAY loadCountGiaiThuong " + GlobalVariables.loadCountGiaiThuong(mActivity, GlobalVariables.SO_TAY));
			Log.v("TEST","ADMIN MOC_KHOA " + data.getDataMockhoa());
			Log.v("TEST","ADMIN MOC_KHOA loadCountGiaiThuong " + GlobalVariables.loadCountGiaiThuong(mActivity, GlobalVariables.MOC_KHOA));
    	}
    }
    
	public void setDataGame(ObjRecordData data)
	{
		GlobalVariables.defaultRecordData = data;
	}
    
	public String getCurrentDate()
	{
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		String date = df.format(Calendar.getInstance().getTime());
		
		return date;
	}
    
	public void resetVariblesPost()
	{
		GlobalVariables.lstData.clear();
		GlobalVariables.index = 0;
		GlobalVariables.id_giai_thuong = 1;
	}
	
	public void setVariablesPost()
	{
		GlobalVariables.id_giai_thuong++;
		if(GlobalVariables.id_giai_thuong > 5)
		{
			GlobalVariables.index++;
			if(GlobalVariables.index < GlobalVariables.lstData.size())
			{
				Log.v("TEST", "GlobalVariables.index < GlobalVariables.lstData.size - postToServer");
				GlobalVariables.id_giai_thuong = 1;
				if(!getCurrentDate().equals(GlobalVariables.lstData.get(GlobalVariables.index).getDate()))
						{
						    db.deleteItemsRecordData(GlobalVariables.lstData.get(GlobalVariables.index));
						}
				postToServer();
			}else{
				Log.v("TEST", "resetVariblesPost - postRecordUserToServer");
				resetVariblesPost();
				if(GlobalVariables.lstUser.size() != 0)
				{
					postRecordUserToServer();
				}else{

					ProcessData.showDialogThongbao(mContext, getResources().getString(R.string.txt_dongboComplete));
					closeDialog();
// 					deleteAllData();
// 					showDialogDeleteData();
				}
			}
		}else{
			Log.v("TEST", "GlobalVariables.id_giai_thuong <5 - postToServer");
			postToServer();
		}
	}
	
	public void setVariablePostRecordUser()
	{
		GlobalVariables.indexUser++;
		if(GlobalVariables.indexUser < GlobalVariables.lstUser.size())
		{
			postRecordUserToServer();
		}else{
			GlobalVariables.lstUser.clear();
			GlobalVariables.indexUser = 0;
// 			postCompleted = true;
// 			deleteAllData();
			closeDialog();
			ProcessData.showDialogThongbao(mContext, getResources().getString(R.string.txt_dongboComplete));
// 			showDialogDeleteData();
			Log.v("TEST", "complete");
		}
	}
	
    public void postToServer()
    {
		try {
			onLoadDataToServer(GlobalVariables.id_giai_thuong, GlobalVariables.lstData.get(GlobalVariables.index));
		} catch (Exception e) {
			// TODO: handle exception
		}
    }
    
    public void onLoadDataToServer(int id_giai_thuong, ObjRecordData recordData) {
		try {
			new LoadDataDataToServer(id_giai_thuong, recordData).execute();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	class LoadDataDataToServer extends AsyncTask<Void, Void, JSONObject> {
		private int id_giai_thuong;
		private ObjRecordData recordData;

		public LoadDataDataToServer(int id_giai_thuong, ObjRecordData recordData) {
			this.id_giai_thuong = id_giai_thuong;
			this.recordData = recordData;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected JSONObject doInBackground(Void... params) {
		JSONObject data = ProcessData.postRecordData(id_giai_thuong, recordData);
			return data;
		}

		@Override
		protected void onPostExecute(JSONObject result) {
//			Log.v("TEST", "data get edit: " + result);
			if (result != null) {
				String status;
				try {
					status = result.getString("status");

					if(status.equals("true"))
					{
						setVariablesPost();
					}else{

						closeDialog();
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}else{

				closeDialog();
			}
			
			super.onPostExecute(result);
		}
	}
	
    public void postRecordUserToServer()
    {
		try {
			onLoadDataUserToServer(GlobalVariables.lstUser.get(GlobalVariables.indexUser));
		} catch (Exception e) {
			// TODO: handle exception
		}
    }
    
	public void onLoadDataUserToServer(ObjUser recordUser) {
		try {
			new LoadDataUserToServer(recordUser).execute();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	class LoadDataUserToServer extends AsyncTask<Void, Void, JSONObject> {
		private ObjUser recordUser;

		public LoadDataUserToServer(ObjUser recordUser) {
			this.recordUser = recordUser;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected JSONObject doInBackground(Void... params) {
		JSONObject data = ProcessData.postRecordUser(recordUser);
			return data;
		}

		@Override
		protected void onPostExecute(JSONObject result) {
//			Log.v("TEST", "data get edit: " + result);
			if (result != null) {
				String status;
				try {
					status = result.getString("status");

					if(status.equals("true"))
					{
						//delete items
						db.deleteItemsRecordUsers(recordUser);
						setVariablePostRecordUser();
					}else{

						closeDialog();
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}else{

				closeDialog();
			}
			
			super.onPostExecute(result);
		}
	}
}
